# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging,sys,threading,time

from piHAlibs import (adstr2addr,confgetval)
from .corecmds import (AdminCmds)
from .corelibs import (sysevents)
from .coresetup import (Servers,SetupDaemons)
from .parsecmds import (ParseCMDS)
from .rpccmds import (RPCFunctions)
from .rpclcmds import (RPCLocalFunctions)

logger = logging.getLogger()


def startalls(trx=True,rpcsap='',tcprap='',tcpsap=''):
    if rpcsap !=  '':
        if rpcsap == 'Defaults':
            rpcs = Servers['RPCS']()
            rpcs.Functions += RPCFunctions
            rpcs.Functions += RPCLocalFunctions
        else:
            rpcs = Servers['RPCS'](adstr2addr(rpcsap))
            rpcs.Functions += RPCFunctions
        rpcs.tsetup()
        rpcs.starts()
        SetupDaemons.setdefault('RPCS')
        SetupDaemons['RPCS'] = rpcs

    if trx and tcprap !=  '':
        if tcprap == 'Defaults':
            tcprx = Servers['TCPRX']()
        else:
            tcprx = Servers['TCPRX'](adstr2addr(tcprap))
        tcprx.tsetup()
        tcprx.starts()
        SetupDaemons.setdefault('TCPRX')
        SetupDaemons['TCPRX'] = tcprx

    if tcpsap !=  '':
        if tcpsap == 'Defaults':
            tcps = Servers['TCPS']()
        else:
            tcps = Servers['TCPS'](adstr2addr(tcpsap))
            tcps.Functions.update(ParseCMDS)
        tcps.tsetup()
        tcps.starts()
        SetupDaemons.setdefault('TCPS')
        SetupDaemons['TCPS'] = tcps


def startsysf(daemon=True):
    fsyslog  = confgetval('pimucha.conf','ServersArgs','SYSLogfile','sysevents.log')
    syslogf = Servers['SYSLOGF'](fsyslog)
    syslogf.features.append(sysevents(AdminCmds))
    syslogf.tsetup()
    if not syslogf.setup : return False
    syslogf.starts(daemon)
    SetupDaemons.setdefault('SYSLOGF')
    SetupDaemons['SYSLOGF'] = syslogf

    inparser = Servers['INParser']()
    inparser.Functions.update(ParseCMDS)
    inparser.tsetup()
    inparser.starts()
    SetupDaemons.setdefault('INParser')
    SetupDaemons['INParser'] = inparser
    return True
